using System;
using System.Collections.Generic;
using Edge.Common;
using Edge.Common.ComponentModel.Notification;
using Edge.Common.Services;
using Edge.Common.Utils;
using Edge.DAL.Common;
using Edge.DAL.Managers;
using NHibernate;
using NHibernate.Expression;
using NHibernate.Type;
using Shop.Business.Domain.Customers;
using Shop.Business.Domain.Orders;
using Shop.Business.Domain.Pricing;
using Order = Shop.Business.Domain.Orders.Order;

namespace Shop.DAL.Managers
{
    class PriceItemManager : AbstractManager<PriceItem, int, Customer>, IPriceItemManager
    {
        public ICollection<PriceItem> Find(FetchOptions fetchOptions, PriceItemFilter filter)
        {
            ICriteria criteria = CreateCriteria(fetchOptions);
            AddRestrictions(criteria, filter);
            return criteria.List<PriceItem>();
        }

        public int Count(PriceItemFilter filter)
        {
            ICriteria criteria = CreateCriteria();
            AddRestrictions(criteria, filter);
            criteria.SetProjection(Projections.RowCount());
            return (int)criteria.List()[0];
        }


        private void AddRestrictions(ICriteria criteria, PriceItemFilter filter)
        {
            if (filter.Product != null)
                criteria.Add(Expression.Eq("Product", filter.Product));
            if (filter.Price > 0)
                criteria.Add(Expression.Eq("Price", filter.Price));
            if (filter.WholesellPrice > 0)
                criteria.Add(Expression.Between("WholesellPrice", filter.WholesellPrice - 5, filter.WholesellPrice + 5));
        }

        public void SetProductInvisible(string guid)
        {
            using (IDalOperation op = CreateLoadOperation())
            {
                IQuery query = Session.GetNamedQuery("SetProductsInvisible");
                query.SetParameter("guid", guid, TypeFactory.Basic("string"));
                query.UniqueResult();
                op.Commit();
            }
        }


    }
}